import Dialog from '@vant/weapp/dialog/dialog'

Page({
  data: {
    records: [],
    pageSize: 30,
    loading: false,
    hasMore: true,
    defaultImage: '/images/default-food.png'
  },

  onLoad() {
    this.loadRecords()
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({
      records: [],
      hasMore: true
    })
    await this.loadRecords()
    wx.stopPullDownRefresh()
  },

  // 上拉加载
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadRecords()
    }
  },

  // 加载记录
  async loadRecords() {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const db = wx.cloud.database()
      const _ = db.command
      
      // 查询数据
      const res = await db.collection('cooking')
        .where({
          _openid: '{openid}' // 云开发会自动替换为当前用户的openid
        })
        .orderBy('createTime', 'desc')
        .skip(this.data.records.length)
        .limit(this.data.pageSize)
        .get()

      if (!res.data.length) {
        this.setData({ hasMore: false })
        return
      }

      // 处理数据
      const newRecords = res.data.map(record => ({
        ...record,
        displayDate: this.formatDate(record.createTime),
        duration: this.calculateDuration(record.timeRange),
        showAllIngredients: false
      }))

      // 更新列表
      this.setData({
        records: [...this.data.records, ...newRecords]
      })

    } catch (err) {
      console.error('加载记录失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 格式化日期
  formatDate(dateStr) {
    const date = new Date(dateStr)
    const now = new Date()
    const diff = now - date
    const oneDay = 24 * 60 * 60 * 1000

    if (diff < oneDay) {
      return '今天'
    } else if (diff < oneDay * 2) {
      return '昨天'
    } else {
      return `${date.getMonth() + 1}-${date.getDate()}`
    }
  },

  // 计算耗时
  calculateDuration({ start, end }) {
    const startTime = new Date(start)
    const endTime = new Date(end)
    const diff = endTime - startTime
    const minutes = Math.floor(diff / 1000 / 60)
    
    if (minutes < 60) {
      return `${minutes}分钟`
    } else {
      const hours = Math.floor(minutes / 60)
      const remainMinutes = minutes % 60
      return `${hours}小时${remainMinutes}分钟`
    }
  },

  // 展开/收起食材
  toggleIngredients(e) {
    const { index } = e.currentTarget.dataset
    const key = `records[${index}].showAllIngredients`
    this.setData({
      [key]: !this.data.records[index].showAllIngredients
    })
  },

  // 图片加载失败
  onImageError(e) {
    const { index } = e.currentTarget.dataset
    const key = `records[${index}].images[0]`
    this.setData({
      [key]: this.data.defaultImage
    })
  },

  // 删除记录
  onDelete(e) {
    const { id } = e.currentTarget.dataset
    
    Dialog.confirm({
      title: '确认删除',
      message: '删除后无法恢复，是否继续？'
    }).then(async () => {
      try {
        await wx.cloud.callFunction({
          name: 'deleteCookingRecord',
          data: { id }
        })

        // 更新列表
        const records = this.data.records.filter(item => item._id !== id)
        this.setData({ records })

        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
      } catch (err) {
        console.error('删除失败:', err)
        wx.showToast({
          title: '删除失败',
          icon: 'error'
        })
      }
    })
  },

  // 跳转到详情页
  goToDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/cooking-detail/cooking-detail?id=${id}`
    })
  },

  // 跳转到添加页面
  goToAdd() {
    wx.navigateTo({
      url: '/pages/add-cooking/add-cooking'
    })
  }
}) 